package com.cdtye.shuoh.controller.play;

import com.cdtye.shuoh.config.gb28181.bean.RecordInfo;
import com.cdtye.shuoh.config.gb28181.transmit.callback.DeferredResultHolder;
import com.cdtye.shuoh.config.gb28181.transmit.callback.RequestMessage;
import com.cdtye.shuoh.config.gb28181.transmit.cmd.impl.SIPCommander;
import com.cdtye.shuoh.domain.device.entity.Device;
import com.cdtye.shuoh.service.device.DeviceService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

/**
 * GB28181 国标录像
 * @author ZhongWang Wang
 * @date 2022-12-21
 */
@RestController
@RequestMapping(value = "/record")
@ConditionalOnProperty(value = "sip.enabled", havingValue = "true")
public class RecordController {
    private final static Logger logger = LoggerFactory.getLogger(RecordController.class);

    @Autowired
    private SIPCommander cmder;

    @Autowired
    private DeferredResultHolder resultHolder;

    @Autowired
    private DeviceService deviceService;

    @GetMapping("/recordInfo")
    public DeferredResult<ResponseEntity<RecordInfo>> recordInfo( String deviceIdentification, String channelId, String startTime, String endTime){

        if (logger.isDebugEnabled()) {
            logger.debug(String.format("录像信息查询 API调用，deviceIdentification：%s ，startTime：%s， startTime：%s",deviceIdentification, startTime, endTime));
        }

        Device device = deviceService.findOneByDeviceIdentification(deviceIdentification);
        cmder.recordInfoQuery(device, channelId, startTime, endTime);
        // 指定超时时间 1分钟30秒
        DeferredResult<ResponseEntity<RecordInfo>> result = new DeferredResult<ResponseEntity<RecordInfo>>(90*1000L);
        resultHolder.put(DeferredResultHolder.CALLBACK_CMD_RECORDINFO+deviceIdentification, result);
        result.onTimeout(()->{
            RequestMessage msg = new RequestMessage();
            msg.setDeviceId(deviceIdentification);
            msg.setType(DeferredResultHolder.CALLBACK_CMD_RECORDINFO);
            msg.setData("timeout");
            resultHolder.invokeResult(msg);
        });
        return result;
    }
}
